<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="版本名称" prop="versionName">
        <el-input v-model="queryParams.search.versionName" placeholder="请输版本名称" clearable size="small"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="版本号" prop="versionNo">

        <el-input v-model="queryParams.search.versionNo" placeholder="请输版本号" clearable size="small"
          @keyup.enter.native="handleQuery" />

      </el-form-item>
      <el-form-item label="业务类型" prop="typeName">
        <!-- <el-select v-model="queryParams.apkSearch.channelType" placeholder="请选择渠道" @change="changeChannelSelect">
          <el-option v-for="item in channelList" :key="item.channelType" :label="item.channelName"
            :value="item.channelType"
          </el-option>
        </el-select> -->
        <el-select v-model="queryParams.search.typeName" placeholder="请选择业务类型">
          <el-option v-for="item in channelList2" :key="item" :label="item" :value="item">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="所属区域" prop="areaName">
        <el-select v-model="queryParams.search.areaName" placeholder="请选择所属区域" @change="changeChannelArea">
          <el-option v-for="item in channelList1" :key="item" :label="item" :value="item">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-apkSearch" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['system:user:add']">新增</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="versionList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="版本号" align="center" prop="versionNo" />
      <el-table-column label="版本名称" align="center" prop="versionName" />
      <el-table-column label="版本升级说明" align="center" prop="remark" />
      <el-table-column label="业务类型" align="center" prop="typeName" />
      <el-table-column label="所属区域" align="center" prop="areaName" />
      <el-table-column label="下载地址" align="center" prop="fileUrl" width="180">
        <template slot-scope="scope">
          <span>{{ scope.row.fileUrl }}</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-download" @click="downLoad(scope.row)">下载</el-button>
          <!-- <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button> -->
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.current" :limit.sync="queryParams.pageSize"
      @pagination="getList" />
    <!-- 添加或修改账户管理对话框 -->
    <!-- -->
    <el-dialog :title="dialogConfig.title" :visible.sync="dialogConfig.visible" width="40%" append-to-body>
      <el-form ref="form" :inline="true" :rules="rules" :model="form" label-width="100px">
        <el-row :span="24">
          <el-col :span="12">
            <el-form-item label="版本名称" prop="versionName">
              <el-input v-model="form.versionName" placeholder="请输版本名称" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="版本号" prop="versionNo">
              <el-input v-model="form.versionNo" placeholder="请输版本号" clearable />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="业务类型" prop="type">
              <el-select v-model="form.type" placeholder="请选择业务类型" @change="changeChannelType">
                <el-option v-for="item in channelList2" :key="item" :label="item" :value="item">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属区域" prop="area">
              <el-select v-model="form.area" placeholder="请选择所属区域" @change="changeChannelArea">
                <el-option v-for="item in channelList1" :key="item" :label="item" :value="item">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
           
            <el-form-item label="版本升级说明">
              <el-input type="textarea" v-model="form.remark" placeholder="请输入版本升级说明" style="width: 550px"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="上传附件" prop="fileUrl">
              <el-upload :file-list="fileList" :on-preview="handlePreview" :on-remove="handleRemove"
                :before-remove="beforeRemove" :headers="headers" :action="uploadImgUrl"
                :on-success="handleUploadSuccess" :on-exceed="handleExceed" accept=".apk">
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">只能上传apk格式，且不超过小于20M</div>

                <!-- 自定义文件列表 -->
                <template #file="scope">
                  <div class='file_index'>
                    <span>{{ scope.file.name }}</span>
                    <el-button class='icon-delete' type="text" icon="el-icon-delete"
                      @click="handleRemove(scope.file, fileList)"></el-button>
                  </div>
                </template>
              </el-upload>

            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>
<script>
import { versionList, getvsList, getVersionList, getvsionList, getAllAreaList, downloadApk, addUser } from "@/api/business/downlist";
import { getToken } from "@/utils/auth";

export default {
  name: "VersionManagement",
  data () {
    return {
      // 上传相关配置
      fileList: [],
      imageUrl: '',
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      uploadImgUrl: process.env.VUE_APP_BASE_API + "/versionApk/upload", // 上传的图片服务器地址

      // 文件列表


      // 表格加载状态
      loading: true,
      type: null,
      // 选中数据
      selectedIds: [],
      single: true,
      multiple: true,

      // 搜索相关
      showSearch: true,
      total: 0,

      // 列表数据
      versionList: [],

      // 弹窗相关
      dialogConfig: {
        title: "",
        visible: false
      },
      // 查询参数
      queryParams: {
        current: 1,
        pageSize: 10,
        search: {
          type: null,
          area: null,
          typeName: null,
          versionName: null,
          versionNo: null,
          areaName: null,
        }
      },
      params: {
        type: null,
      },

      // 下拉选项数据
      channelList: [],
      channelList1: [],
      channelList2: [],


      // 表单数据
      form: {
        fileUrl: null,
        versionNo: null,
        versionName: null,
        version: null,
        remark: null,
        type: null,
        area: null,
        file: null,
        typeName: null,
        areaName: null
      },

      // 表单校验规则
      rules: {
        versionName: [
          { required: true, message: '请输入版本名称', trigger: 'blur' }
        ],
        versionNo: [
          { required: true, message: '请选择版本号', trigger: 'change' }
        ],
        type: [
          { required: true, message: '请选择业务类型', trigger: 'change' }
        ],
        area: [
          { required: true, message: '请选择所属区域', trigger: 'change' }
        ]
      }
    };
  },

  created () {
    this.initData();
    // this.getAreaList();
    this.getvsList();
    this.getvsionList()

  },

  methods: {
    handlePreview () {
      console.log(this.fileList, 'fileList');
    },
    // 初始化数据
    async initData () {
      await this.getList();
      const response = await getVersionList({});

      this.channelList2 = response.data;
    },

    // 获取列表数据
    async getList () {
      this.loading = true;
      try {
        const response = await versionList(this.queryParams);

        this.versionList = response.data.records;
        this.total = response.data.total;
      } finally {
        this.loading = false;
      }
    },
    async getvsList () {
      this.loading = true;
      try {
        const response = await getvsList(this.queryParams);
        this.channelList = response.data
      } finally {
        this.loading = false;
      }
    },
    async getvsionList () {
      this.loading = true;
      try {
        const response = await getvsionList(this.queryParams);
        this.channelList1 = response.data
        console.log(this.channelList1, 'channelList1');
      } finally {
        this.loading = false;
      }
    },
    async getAreaList () {
      this.loading = true;
      try {
        const response = await getAllAreaList(this.type);
        this.versionList = response.data.records;
        this.total = response.data.total;
      } finally {
        this.loading = false;
      }
    },
    // 处理下拉框选择
    handleSelectChange (field, value) {
      const nameField = field + 'Name';
      const selectedItems = this.channelList.filter(item =>
        Array.isArray(value) ? value.includes(item.id) : value === item.id
      );
      this.form[nameField] = selectedItems.map(item => item[nameField]);
    },

    // 搜索相关方法
    handleQuery () {
      this.queryParams.current = 1;
      this.getList();
    },

    resetQuery () {
      this.resetForm("queryForm");
      this.queryParams.search = {
        type: null,
        area: null,
        typeName: null,
        versionName: null,
        versionNo: null,
        areaName: null,
      };
      this.handleQuery();
    },

    // 表格选择相关
    handleSelectionChange (selection) {
      this.selectedIds = selection.map(item => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },

    // 新增相关方法
    handleAdd () {
      this.reset();
      this.dialogConfig = {
        title: "添加版本管理",
        visible: true
      };
    },

    // 表单相关方法
    reset () {
      this.form = {
        type: null,
        area: null,
        typeName: null,
        versionName: null,
        versionNo: null,
        areaName: null,
        fileUrl: null,
        remark: null,
      };
      this.resetForm("form");
      this.fileList = [];
    },

    // 提交表单
    async submitForm () {

      try {
        await this.$refs["form"].validate();

        const submitData = {

          ...this.form,
          typeName: this.form.typeName,  // 直接使用单选值
          areaName: this.form.areaName,  // 直接使用单选值
          type: this.form.type,  // 直接使用单选值
          area: this.form.area,
          fileUrl: this.form.fileUrl

        };
        console.log(submitData, 'submitData');
        await addUser(submitData);
        this.$message.success('添加成功');
        this.dialogConfig.visible = false;
        this.getList();
      } catch (error) {
        this.$message.error('添加失败');
      }
    },


    // },
    handleUploadSuccess (res, file) {
      console.log(res, 'res1111');
      this.form.fileUrl = res.data; // 存储URL
      this.fileList = [file]; // 更新文件列表
    },
    handleRemove (file) {
      this.fileList = [];
      this.form.fileUrl = null;
    },

    handleExceed (files, fileList) {
      this.$message.warning(
        `当前限制选择 ${this.uploadConfig.limit} 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`
      );
    },

    beforeRemove (file) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },

    // 下载文件
    async downLoad (row) {
      try {
        // 从row中获取fileUrl
        // const fileUrl = row.fileUrl;
        // if (!fileUrl) {
        //   this.$message.error('文件地址不存在');
        //   return;
        // }
        // 从URL中提取文件名
        // const fileName = fileUrl.split('/').pop();

        let fileName = row.fileUrl;
        if (!fileName) {
          this.$message.error('无效的文件名');
          return;
        }
        const response = await downloadApk(fileName);
        // 创建Blob对象
        const blob = new Blob([response], { type: 'apk' });
        // // 创建临时链接
        const downloadUrl = window.URL.createObjectURL(blob);
        const ADOM = document.createElement('a');
        ADOM.href = downloadUrl;
        ADOM.download = new Date().getTime() + ".apk";
        ADOM.click();
        console.log(response, blob, downloadUrl,);
        // let decodedString = decodeURIComponent(response.headers['content-disposition'].split(';')[1].split('=')[1]);// 文件名在响应头里，需要后端设置Access - Control - Expose - Headers: Content - Disposition
        // const url = window.URL.createObjectURL(new Blob([response.data]));
        // const link = document.createElement('a');
        // link.href = url;
        // link.setAttribute('download', '协议模版.png'); // 设置下载的文件名
        // document.body.appendChild(link); // 需要添加到文档中
        // link.click(); // 触发下载
        // document.body.removeChild(link);



        this.$message.success('文件下载开始');
      } catch (error) {
        console.error('下载失败:', error);
        this.$message.error('文件下载失败');


      }
    },

    changeChannelArea (value) {
      this.channelList1.find(option => {
        if (option.areaName === value) {
          this.form.areaName = option.areaName
        }
      });


      // let areaName = this.channelList1.filter(item => {
      //   return item.id == value
      // })
      // this.form.areaName = areaName[0] ? areaName[0].areaName : ''
    },

    changeChannelType (value) {
      this.channelList2.find(option => {
        if (option.typeName === value) {

          this.form.typeName = option.typeName
        }
      });
      // let typeName = this.channelList2.filter(item => {
      //   return item.id == value
      // })
      // this.form.typeName = typeName[0] ? typeName[0].typeName : ''

    },
    // 取消按钮
    cancel () {
      this.dialogConfig.visible = false;
      this.reset();
    }
  }
};
</script>

